package com.exam.controller;

import com.exam.exception.StudentNonExist;
import com.exam.pojo.*;
import com.exam.service.*;
import com.exam.util.GradeUtil;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 黄星
 * 问题管理控制器
 */
@Controller
@RequestMapping("/QuestionManage")
public class QuestionManage {

	@Resource(name="mv")
	private ModelAndView mv;
	@Resource(name = "typeServiceImpl")
	private TypeService typeService;
	@Resource(name = "questionServiceImpl")
	private QuestionService questionService;
	@Resource(name = "majorServiceImpl")
	private MajorService majorService;
	@Resource(name = "subjectServiceImpl")
	private SubjectService subjectService;
	@Resource(name = "classesServiceImpl")
	private ClassesService classesService;
	@Resource(name="gson")
	private Gson gson;
	@Resource(name="map")
	private Map map;

	/**
	 * 初始化页面
	 * */
	@RequestMapping("/question-list")
	public ModelAndView questionlist(){

		List<Major> majorList = majorService.getAllMajor();
		List<Type> typeList = typeService.getAllType();
		mv.addObject( "majorList",majorList );
		mv.addObject( "typeList",typeList );
		mv.setViewName( "admin/question-list" );

		return mv;
	}

	/**
	 * 通过分页来获取题目
	 * */
	@RequestMapping("/getQuestionByPaging")
	public void getQuestionByPaging(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter printWriter = response.getWriter();

		Integer page = Integer.parseInt(request.getParameter("page")); //当前页
		Integer majorId = Integer.parseInt( request.getParameter( "majorId" ) );  //专业id
		Integer gradeId = Integer.parseInt( request.getParameter( "gradeId" ) );   //年级
		Integer typeId = Integer.parseInt( request.getParameter( "typeId" ) );   //类型
		Integer subjectId = Integer.parseInt( request.getParameter( "subjectId" ) );  //科目
		Integer pageSize = 10; //页面大小
		Map map = new HashMap();
		map.put("page",page);
		map.put("pageSize",pageSize);
		map.put("majorId",majorId);
		map.put("gradeId",gradeId);
		map.put( "typeId",typeId );
		map.put( "subjectId",subjectId );
		map.put( "status",1);
		Paging<Question> pagingList = questionService.questionPaging(map);
		String s = gson.toJson(pagingList);
		printWriter.write(s);
		printWriter.close();
	}

	/**
	 * 获取对应专业，对应年级  来获取科目信息
	 * */
	@RequestMapping("/getSubjectByMajorAndClasses")
	public void getSubjectByMajorAndClasses(HttpServletRequest request, HttpServletResponse response) throws IOException{

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter printWriter = response.getWriter();

		Integer majorId = Integer.parseInt( request.getParameter( "majorId" ) );
		List<Classes> classes = classesService.getClassesByMajorId( majorId );  //获取到该专业的所有班级
		Integer gradeId = Integer.parseInt( request.getParameter( "gradeId" ) );
		//通过年级来获取班级名前两位，进而获得班级的id，通过专业id与班级id来获取专业
		String claasesName = GradeUtil.getGrade( gradeId );
		Integer classesId = 0;
		List<Subject> subjectList = new ArrayList<Subject>(  );
		for(int i = 0;i < classes.size();i++){
			if(classes.get( i ).getClassesName().contains(claasesName  )){
				classesId = classes.get( i ).getId();
				List<Subject> subs = subjectService.getSubjectByMajorIdAndClassesId( majorId, classesId );
				for(int j = 0 ; j < subs.size();j++){
					subjectList.add( subs.get( j ) );
				}
			}
		}

		Paging<Subject> paging = new Paging<Subject>();
		paging.setList( subjectList );
		String s = gson.toJson(paging);
		printWriter.write(s);
		printWriter.close();

	}

	/**
	 * 删除问题
	 * */
	@RequestMapping("/deleteQuestion")
	public void deleteQuestion(HttpServletRequest req,HttpServletResponse resp) throws IOException {

		resp.setContentType("text/xml;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		Integer questionId = Integer.parseInt( req.getParameter( "questionId" ) );
		if(questionService.delQuestionById( questionId ) > 0){
			out.println( "{\"res\":\"删除成功\"}" );
		}else{
			out.println( "{\"res\":\"删除失败\"}" );
		}
	}

	/**
	 * 修改问题页面
	 * 能够修改所属专业  所属年级   所属科目
	 * */
	@RequestMapping("/question-update")
	public ModelAndView updateQuestion(HttpServletRequest req,HttpServletResponse resp) {

		Integer questionId = Integer.parseInt( req.getParameter( "questionId" ) );
		//先获取问题的信息
		Question question = questionService.getQuestionById( questionId );
		Integer majorId = question.getSubject().getMajorId();

		Integer classesId = question.getSubject().getClassesId();
		Integer gradeId = GradeUtil.getGradeId( classesService.getClassesById( classesId ).getClassesName() );//传到前台  显示是大几 1 2 3 4
		List<Major> majorList = majorService.getAllMajor();    //传到前台   所有专业
		List<Subject> subjectList = subjectService.getSubjectByMajorId( majorId );//要传到前台  该专业的所有科目
		List<Type> typeList = typeService.getAllType();    //传到前台 显示所有类型
		List<String> retStr = new ArrayList<String>(  );   //返回分割的题目  或 填空题题目
		if(question.getType().getId() == 1){
			//如果该问题是选择题
			String[] split = question.getErrAnswer().split( "~" );
			for(int i = 0;i < split.length;i++){
				retStr.add( split[i] );
			}
		}else if(question.getType().getId() == 2){
			//如果该问题是填空题
			String[] split = question.getTopic().split( "_" );
			for(int i = 0;i < split.length;i++){
				retStr.add( split[i] );
			}
			if(split.length == 1){
				retStr.add( "" );
			}
		}
		//要显示问题的ID  问题的专业 ， 所属年级，  所属专业
		mv.addObject( "question",question );
		mv.addObject( "gradeId",gradeId );
		mv.addObject( "majorList", majorList);
		mv.addObject( "subjectList",subjectList );
		mv.addObject( "typeList",typeList );
		mv.addObject( "split",retStr );
		mv.setViewName( "/admin/question-update" );
		return mv;
	}

	/**
	 * 根据对应专业，对应年级  来获取科目信息
	 * 以修改题目
	 * */
	@RequestMapping("/getSubjectToUpdate")
	public void getSubjectToUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException{

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter printWriter = response.getWriter();

		Integer majorId = Integer.parseInt( request.getParameter( "majorId" ) );
		List<Classes> classes = classesService.getClassesByMajorId( majorId );  //获取到该专业的所有班级
		Integer gradeId = Integer.parseInt( request.getParameter( "gradeId" ) );
		List<Subject> subjectList = new ArrayList<Subject>(  );
		if(gradeId == 0){
			subjectList = subjectService.getSubjectByMajorId( majorId );
		}else{
			String claasesName = GradeUtil.getGrade( gradeId );
			Integer classesId = 0;
			for(int i = 0;i < classes.size();i++){
				if(classes.get( i ).getClassesName().contains(claasesName  )){
					classesId = classes.get( i ).getId();
					List<Subject> subs = subjectService.getSubjectByMajorIdAndClassesId( majorId, classesId );
					for(int j = 0 ; j < subs.size();j++){
						subjectList.add( subs.get( j ) );
					}
				}
			}
		}

		Paging<Subject> paging = new Paging<Subject>();
		paging.setList( subjectList );
		String s = gson.toJson(paging);
		printWriter.write(s);
		printWriter.close();
	}

	/**
	 * 更新确定点击后 修改控制器
	 * */
	@RequestMapping("/updQuestion")
	public void updQuestion(HttpServletRequest req, HttpServletResponse resp) throws IOException{

		resp.setContentType("text/xml;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding( "utf-8" );
		PrintWriter out = resp.getWriter();

		Integer typeId = Integer.parseInt( req.getParameter( "typeId" ) );

		switch (typeId){
			case 1:
				//选择题
				map.put( "topic",req.getParameter( "topic" ) );
				map.put( "answer",req.getParameter( "answer" ) );
				map.put( "errAnswer",req.getParameter( "errAnswer" ) );
				break;
			case 2:
				//填空题
				map.put( "topic",req.getParameter( "topic" ) );
				map.put( "answer",req.getParameter( "answer" ) );
				map.put( "errAnswer","" );
				break;
			case 3:
				//判断题
				map.put( "topic",req.getParameter( "topic" ) );
				map.put( "answer","" );
				map.put( "errAnswer",req.getParameter( "errAnswer" ) );
				break;
		}

		//填入参数 调用更新
		map.put( "questionId",Integer.parseInt( req.getParameter( "questionId" ) ));
		map.put( "subjectId",Integer.parseInt( req.getParameter( "subjectId" ) ));
		map.put( "typeId",typeId );

		if(questionService.updQuestion( map ) > 0){
			out.println( "修改成功" );
		}else {
			out.println( "修改失败" );
		}
	}

	/**
	 * 题目的添加
	 * */
	@RequestMapping("question-add")
	public ModelAndView Questionadd(){

		mv.setViewName( "admin/question-add" );
		mv.addObject( "majorList",majorService.getAllMajor() );

		return mv;
	}

	/**
	 * 添加题目页面的确定按钮点击后
	 * */
	@RequestMapping("addQuestion")
	public void addQuestion(HttpServletRequest req,HttpServletResponse resp) throws IOException {

		resp.setContentType("text/xml;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding( "utf-8" );
		PrintWriter out = resp.getWriter();

		Integer typeId = Integer.parseInt( req.getParameter( "typeId" ) );

		switch (typeId){
			case 1:
				//选择题
				map.put( "topic",req.getParameter( "choiceTopic" ) );
				map.put( "answer",req.getParameter( "choiceAnswer" ) );
				String errAnswer = req.getParameter( "choiceErrAnswer1" );
				errAnswer += ("~"+ req.getParameter( "choiceErrAnswer2" ));
				errAnswer += ("~"+req.getParameter( "choiceErrAnswer3" ));
				map.put( "errAnswer",errAnswer );
				break;
			case 2:
				//填空题
				String topic = req.getParameter( "blankBeforeTopic" ) + "_" + req.getParameter( "blankAfterTopic" );
				map.put( "topic",topic );
				map.put( "answer",req.getParameter( "blankAnswer" ) );
				map.put( "errAnswer","" );
				break;
			case 3:
				//判断题
				map.put( "topic",req.getParameter( "judgeTopic" ) );
				map.put( "answer","" );
				map.put( "errAnswer",req.getParameter( "judgeErrAnswer" ) );
				break;
		}

		map.put( "subjectId",Integer.parseInt( req.getParameter( "subjectId" ) ));
		map.put( "typeId",typeId );

		if(questionService.addQuestion( map ) > 0){
			out.println( "添加成功" );
		}else {
			out.println( "添加失败" );
		}
	}

	/**
	 * 已删除题目界面
	 * */
	@RequestMapping("/delQuestion-list")
	public ModelAndView delQuestionlist(){

		List<Major> majorList = majorService.getAllMajor();
		List<Type> typeList = typeService.getAllType();
		mv.addObject( "majorList",majorList );
		mv.addObject( "typeList",typeList );
		mv.setViewName( "admin/delquestion-list" );
		return mv;
	}

	/**
	 * 删除题目通过分页获取
	 * */
	@RequestMapping("/getDelQuestionByPaging")
	public void getDelQuestionByPaging(HttpServletRequest request,HttpServletResponse response) throws IOException {

		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter printWriter = response.getWriter();

		Integer page = Integer.parseInt(request.getParameter("page")); //当前页
		Integer majorId = Integer.parseInt( request.getParameter( "majorId" ) );
		Integer gradeId = Integer.parseInt( request.getParameter( "gradeId" ) );
		Integer typeId = Integer.parseInt( request.getParameter( "typeId" ) );
		Integer subjectId = Integer.parseInt( request.getParameter( "subjectId" ) );
		Integer pageSize = 10; //页面大小
		Map map = new HashMap();
		map.put("page",page);
		map.put("pageSize",pageSize);
		map.put("majorId",majorId);
		map.put("gradeId",gradeId);
		map.put( "typeId",typeId );
		map.put( "subjectId",subjectId );
		map.put( "status",0);
		Paging<Question> pagingList = questionService.questionPaging(map);
		String s = gson.toJson(pagingList);
		printWriter.write(s);
		printWriter.close();

	}

	/**
	 * 恢复删除题目
	 * */
	@RequestMapping("/questionRecovery")
	public void questionRecovery(HttpServletRequest req,HttpServletResponse resp) throws IOException {

		resp.setContentType("text/xml;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter printWriter = resp.getWriter();

		int questionId = Integer.parseInt( req.getParameter( "questionId" ) );
		if(questionService.recoveryQuestion( questionId ) > 0 ){
			printWriter.println( "恢复成功" );
		}else{
			printWriter.println( "恢复失败" );
		}

	}

	/**
	 * 批量删除题目
	 * */
	@RequestMapping("/deleteQuestionByQuery")
	public void deleteQuestionByQuery(HttpServletRequest req,HttpServletResponse resp) throws IOException {

		PrintWriter printWriter = resp.getWriter();
		String list = req.getParameter("questionIdList");
		String[] list1 = gson.fromJson(list,String[].class); //获取要删除的学生编号

		for(String questionId:list1) { //循环遍历删除
			questionService.delQuestionById( Integer.parseInt(questionId) );
		}
		printWriter.write("{\"res\":\"1\"}");
		printWriter.close();
	}

	/**
	 * 批量恢复题目
	 * */
	@RequestMapping("/recoveryQuestionByQuery")
	public void recoveryQuestionByQuery(HttpServletRequest req,HttpServletResponse resp) throws IOException {

		PrintWriter printWriter = resp.getWriter();
		String list = req.getParameter("questionIdList");
		String[] list1 = gson.fromJson(list,String[].class); //获取要删除的学生编号

		for(String questionId:list1) { //循环遍历删除
			questionService.recoveryQuestion( Integer.parseInt(questionId) );
		}
		printWriter.write("{\"res\":\"1\"}");
		printWriter.close();
	}
}
